import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xbaistack/common/gen.dart'; // 末尾有贴，道友莫慌~

import 'package:xbaistack/l10n/language.dart';
import 'package:xbaistack/utils/helper.dart';
import 'package:xbaistack/widget/group_setting.dart';
import 'package:xbaistack/provider/language_provider.dart';

class SelectLanguePage extends StatelessWidget {
  const SelectLanguePage({super.key});

  @override
  Widget build(BuildContext context) {
    final items = <Item>[];
    final provider = context.watch<AppLocaleProvider>(); // 监听 Provider 状态变更
    final selected = provider.language; // 之前选择的语言

    // 测试信息
    // print("当前语言：$selected");

    // 跟随系统
    items.add(
      Item.select(
        title: context.l10n.followSystem,
        value: provider.isFollowSystem,
        onChanged: (value) {
          if (Helper.isNotEmpty(selected)) {
            provider.saveLanguage(null);
            provider.refresh();
          }
        },
      ),
    );

    // 相关性描述标签
    items.add(Item.leading(context.l10n.languageFollowSystemDescription));

    // 循环添加支持的所有语言列表
    Language.locales.forEach((language, label) {
      items.add(
        Item.select(
          title: label,
          value: selected == language,
          onChanged: (value) {
            if (selected != language) {
              provider.saveLanguage(language);
              provider.refresh();
            }
          },
        ),
      );
    });

    // 页面的主题框架
    return Scaffold(
      appBar: AppBar(title: Text(context.l10n.setLanguage)),
      body: GroupSetting(children: items), // Flutter | 第16期 - 通用设置页
    );
  }
}
